<script type="text/javascript" src="jquery.js"></script>
<script>

var ajax = null;		
var pattern = "";
var server ="";
var service = "";
var hostname = "";	
var progressTimer = null;
var messageTimer = null;
var saveTimer = null;

function callAjax(data){
	if (window.XMLHttpRequest) {
		ajax = new XMLHttpRequest();
		var parameters = "url=" + data.url + "&hq=" + data.quality + "&server="+ server+ "&lang="+data.lang + "&adblock=" + data.adblock;
		update_time = new Date().getTime();
		ajax.open("POST", "http://www.video2mp3.net/check.php", true);
		ajax.onreadystatechange = refresh_ajax;
		ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajax.setRequestHeader("Content-length", parameters.length);
		ajax.setRequestHeader("Connection", "close");
		ajax.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
		ajax.send(parameters);
	}
};

function refresh_ajax() {	
	if (ajax.readyState == 4) {       
		var response = ajax.responseText.split("|");
		if(ajax.status == 404) {   
			
		}	 
		if((ajax.status != 200 || ajax.responseText=="" || (response[0] == "MESSAGE" && response[4]!="ok")) && pattern!="" && service!="") {	
			ajax.open("GET", "http://www.video2mp3.net/update.php?v=" + pattern + "&service=" + service + "&hostname=" + hostname, true);		
			ajax.onreadystatechange = refresh_ajax;
			ajax.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');		
			setTimeout('ajax.send(null)', 1000);	 
		}	 
		else if(response[0] == "ERROR") {
			
		}	 
		else if (response[0] == "WAIT") {	 
			var countdown_total = parseInt(parseInt(response[1])*10);
			var downloaduri = response[5].replace(/^.*YouTube/i,'http://www.video2mp3.net/load/YouTube');
			console.log('source: ',response[5]);
			console.log('target: ',downloaduri);
			chrome.tabs.getSelected(null, function(tab) {
				var data = tab.id.toString()+'|'+downloaduri+'|'+countdown_total.toString();
				if (!localStorage['lastrequest']){
					localStorage['lastrequest']=data;
					setTimeout("onStartRequest()",200);
				}
			});			
		}
		else if (response[0] == "REDIRECT") {
			var downloaduri = response[1].replace(/^.*YouTube/i,'http://www.video2mp3.net/load/YouTube');
			console.log('REDIRECT: ',response[1]);
			window.messageTimer = setTimeout('onMessageArrived(100,"'+downloaduri+'")', 100);
			return false;
		}
		else if (response[0] == "MESSAGE") {
			if(response[4]=="ok") {
				pattern=response[2];
				service=response[3];
				if (response[5]!==''){
					hostname=response[5];
				}
			}
			ajax.open("GET", "http://www.video2mp3.net/update.php?v=" + pattern + "&service=" + service + "&hostname=" + hostname, true);
			ajax.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');		
			ajax.onreadystatechange = refresh_ajax;
			$(response[1]).each(function(index){
				if (this.nodeName=='H2'){
					var txt = this.innerText;
					if (txt!==''){
						console.log(txt);
						var perc = Math.round(parseInt(txt.replace(/\%/i,''))).toString();
						window.messageTimer = setTimeout('onMessageArrived('+perc+',null)', 100);
						return false;
					}
				}
			});
			window.progressTimer = setTimeout('ajax.send(null)', 1000);
		}
		else if (response[0] == "OKCONVERT") {
			console.log('OKCONVERT: ',[10]);
			var data = response;
			return false;
		}
		else {
			console.log('OTHER: ',ajax.responseText);
			var data = ajax.responseText;
			return false;
		}
	}
}

function onMessageArrived(perc,uri)
{
	chrome.tabs.getSelected(null, function(tab) {
		var msg = { action: 'tick', data: {	value : perc, downloaduri : uri	} };
		chrome.tabs.sendRequest(tab.id,msg,function(res){
			console.log(res.status);
		});
	});
	if (messageTimer){
		window.clearInterval(messageTimer);
		messageTimer=null;
	}
};

function onStartRequest()
{
	var reg = localStorage['lastrequest'];
	if (reg!==undefined){
		var fields = reg.split('|');
		var msg = {
			targetTab:parseInt(fields[0]),
			downloaduri:fields[1],
			countdown_num:parseInt(fields[2]),
			countdown_total:parseInt(fields[2])
		};
		chrome.tabs.sendRequest(msg.targetTab,{action:'start',data:msg},function(res){
			delete localStorage['lastrequest'];
		});
	}
}

function reset(tab,callback)
{
	if (localStorage['lastrequest']!==undefined){
		chrome.tabs.sendRequest(tab.id,{action:'reset'},function(res){
			delete localStorage['lastrequest'];
			if (progressTimer){
				window.clearInterval(progressTimer);
				progressTimer=null;
			}
			if (messageTimer){
				window.clearInterval(messageTimer);
				messageTimer=null;
			}
			callback(tab);
		});
		return;
	}
	else{
		callback(tab);
	}
}

chrome.pageAction.onClicked.addListener(function(tab){
	/*if (!ports[tab.id]){
		var port=chrome.tabs.connect(tab.id,{name: "pipe"});
		ports[tab.id]=port;
		console.log("Connected to "+tab.id.toString());
	}*/

	reset(tab,function(tab){
		chrome.tabs.sendRequest(tab.id,{action:'download'},function(res){
			callAjax(res.data);
		});
	});
});

function init() {
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        if (tab.url.match(/^(http|https)\:\/\/www.youtube.com\/watch\?v\=.*/i)){
			reset(tab,function(tab){
				chrome.pageAction.show(tab.id);
				chrome.pageAction.setIcon({tabId: tab.id, path: 'download_19x19.png'});
			});
        }
    });
}

init();
</script>
